package database;

import org.jetbrains.annotations.NotNull;

import java.sql.*;

public class DatabaseHelper {

    private static final String JDBC_URL = "jdbc:mysql://localhost:3306/studentscore";
    private static final String JDBC_USER = "root";
    private static final String JDBC_PWD = "123456";
    public Connection connection;

    public DatabaseHelper() throws SQLException {
        connection = DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PWD);
    }

    public ResultSet query(String query, Object... params) throws SQLException {
        PreparedStatement preparedStatement = connection.prepareStatement(query);
        for (int i = 0; i < params.length; i++) {
            preparedStatement.setObject(i + 1, params[i]);
        }
        return preparedStatement.executeQuery();
    }

    public int update(String update, Object... params) throws SQLException {
        PreparedStatement preparedStatement = connection.prepareStatement(update);
        for (int i = 0; i < params.length; i++) {
            preparedStatement.setObject(i + 1, params[i]);
        }
        return preparedStatement.executeUpdate();
    }

    public void close() {
        try {
            if (connection != null && !connection.isClosed())
                connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}

